package AdminService

import (
	"context"
	"errors"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	v1 "seawolf-admin-go/api/admin/v1"
	"seawolf-admin-go/internal/model/entity"
	"seawolf-admin-go/utility/MyErrorCode"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/myCaptcha"
	token2 "seawolf-admin-go/utility/token"
	"seawolf-admin-go/utility/tools"
	"strings"
)

func Login(ctx context.Context, req *v1.LoginReq) (*v1.LoginRes, error) {
	// 先进行验证码校验
	if !myCaptcha.VerifyCaptcha(req.CaptchaId, req.VerifyCode) {
		return nil, gerror.NewCode(MyErrorCode.GetErrorCode("AdminService.Login.VerifyCaptcha"))
	}
	// 处理usertype
	if req.UserType != "admin" {
		req.Account = "om:" + req.Account
	}
	aModel, err := GetModelByAccount(ctx, req.Account)
	if err != nil {
		return nil, err
	}
	if aModel == nil {
		return nil, errors.New("账号不存在")
	}
	if req.Type == "hash" {
		if tools.EncryptPasswordHash(req.Password, aModel.PasswordSalt) != aModel.Password {
			return nil, errors.New("密码错误")
		}
	} else {
		if tools.EncryptPassword(req.Password, aModel.PasswordSalt) != aModel.Password {
			return nil, errors.New("密码错误")
		}
	}
	if aModel.Status < 1 {
		return nil, errors.New("账号被禁用")
	}
	token, err := token2.GenerateLoginToken(ctx, aModel.Id)
	if err != nil {
		return nil, err
	}
	deptName := ""
	// 取部门名称
	dName, err := db.GetUnSafaTable(ctx, "sys_department").
		Handler(db.SoftDeleteHandler).
		Fields("name").
		Where("status=1 AND id=?", aModel.Id).
		Order("sort ASC").
		Value()
	if err != nil {
		deptName = dName.String()
	}

	// 如果是超级管理员，写入sessionData
	token2.UpdateSessionData(ctx, aModel.Id, g.Map{
		"IsAdmin":  req.Account == "admin",
		"Account":  req.Account,
		"Realname": aModel.Realname,
		"DeptId":   aModel.DeptId,
		"DeptName": deptName,
	})
	return &v1.LoginRes{
		Id:       aModel.Id,
		Account:  aModel.Account,
		DeptId:   aModel.DeptId,
		DeptName: deptName,
		Realname: aModel.Realname,
		Nickname: aModel.Nickname,
		Token:    token,
		UserInfo: &v1.LoginUserInfo{
			UserId:       gconv.String(aModel.Id),
			UserName:     aModel.Account,
			Avatar:       aModel.Avatar,
			AvatarPrefix: "",
			Role:         g.SliceStr{},
		},
	}, nil
}

// 查询用户通过 用户输入的账号
func GetModelByAccount(ctx context.Context, account string) (res *entity.Admin, err error) {
	// 以:开头
	if strings.Index(account, ":") == 0 {
		return nil, errors.New("账号类型不正确1")
	}
	//var am entity.Admin
	//var err error
	// 没有:
	if strings.Index(account, ":") < 0 {
		am, err := GetModelByNoPrefixAccount(ctx, account)
		if err != nil {
			return nil, err
		}
		if am != nil {
			if am.Account != account {
				return nil, errors.New("账号不存在")
			}
		}
		return am, err
	} else {
		s := strings.Split(account, ":")
		if len(s) < 2 {
			return nil, errors.New("账号不正确2")
		}
		if s[0] == "" || s[1] == "" {
			return nil, errors.New("账号不正确3")
		}
		am, err := GetModelByPrefixAccount(ctx, s[1], s[0]+":")
		if err != nil {
			return nil, err
		}
		if am != nil {
			if am.Accountprefix+am.Account != account {
				return nil, errors.New("账号不存在")
			}
		}
		return am, err
	}
	return
}
